package sip

import (
	"github.com/sirupsen/logrus"
	"udp_tcp_client/util"
)

var (
	//回复ack的统一处理
	MessageAckHandlerMap = make(map[string]MessageHandler)
)

func initAckHandlerMap() {
	MessageAckHandlerMap[util.MethodMessage] = HandleAckMessage
	MessageAckHandlerMap[util.MethodNotify] = HandleAckNotify
}

func HandlerAck(message *Message, network string, remoteIp string, remotePort int) (err error) {
	logrus.Infoln(message.Header.CallID, "callId :", message.Header.CallID, " ack 回复 ： code ", message.ResponseLine.StatusCode, "msg ", message.ResponseLine.ReasonPhrase)
	status := message.ResponseLine.StatusCode
	if (status >= util.OkCode && status < util.MultipleChoicesCode) || status == util.UnAuthorizedCode {
		ackHandler := MessageAckHandlerMap[message.Header.CSeq.Method]
		if ackHandler == nil {
			waitChan := ChanMap[message.Header.CallID]
			if waitChan != nil {
				waitChan <- message
				return nil
			}
			return nil
		}
		err = ackHandler(message, network, remoteIp, remotePort)
		return err
	}
	return
}

func HandleAckMessage(message *Message, network string, remoteIp string, remotePort int) (err error) {
	reChan := ChanMap[message.Header.CallID]
	if reChan != nil {
		reChan <- true
	}
	return nil
}

func HandleAckNotify(message *Message, network string, remoteIp string, remotePort int) (err error) {
	reChan := ChanMap[message.Header.CallID]
	if reChan != nil {
		reChan <- true
	}
	return nil
}
